/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mbl.base.core.modular.log.factory;

import com.alibaba.fastjson.JSON;
import com.mbl.base.config.security.SecurityUser;
import com.mbl.base.core.common.constant.SpringContextHolder;
import com.mbl.base.core.modular.log.LogManager;
import com.mbl.base.core.utils.UtilHttp;
import com.mbl.base.core.utils.UtilSecurity;
import com.mbl.base.modular.base.entity.Log;
import com.mbl.base.modular.base.service.ILogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;

/**
 * 日志操作任务创建工厂
 *
 * @author fengshuonan
 * @date 2016年12月6日 下午9:18:27
 */
public class LogTaskFactory {

    private static Logger logger = LoggerFactory.getLogger(LogManager.class);
    private static ILogService loginLogMapper = SpringContextHolder.getBean(ILogService.class);
    /**
     * 访问日志
     * @return
     */
    public static void visitLog(String result) {
        final Log log = new Log();
        SecurityUser user = UtilSecurity.getUser();
        if(user != null){
            log.setAdmin(String.valueOf(user.getId()));
            log.setCreateUser(user.getId());
            log.setUpdateUser(user.getId());
        }
        log.setIp(UtilHttp.getIpAddr());
        log.setType(1);
        log.setStatus(true);
        log.setAction("访问");
        log.setResult(result);
        log.setMUrl(UtilHttp.getRequest().getRequestURI());
        log.setComment(JSON.toJSONString(UtilHttp.getRequest().getParameterMap()));
        LogManager.me().executeLog( new TimerTask() {
            @Override
            public void run() {
                try {
                    loginLogMapper.save(log);
                } catch (Exception e) {
                    logger.error("创建日志异常!", e);
                }
            }
        });
    }
}
